import prodSave from "@/utils/my";
import OrderService from "@/api/order/OrderService.js";
import {
    Loading
} from "element-ui";
import {
    mapMutations,
    mapState
} from "vuex";
import {
    deepAssign
} from '../utils/clone'
export default {
    data() {
        return {
            orderItemInfors: {
                custSoNumber: this.$route.query.customerOrder.custSoNumber || '', //页面初始化流水号,
                custId: "",
                custName: "",
                accepteRegionId: "",
                commonRegionId: "",
                createStaff: "",
                createOrgId: "",
                productId: JSON.parse(sessionStorage.getItem("ppmCondition")).prodId,
                attrId: "",
            },
            activeName: "first",
            radio1: "上海",

            productId: JSON.parse(sessionStorage.getItem("ppmCondition")).prodId,
            resultDate: "",
            customerOrder: {},

            rule: [],
            res: {
                agentList: [],
                result: [],
                custOrderId: this.$route.query.customerOrder.custOrderId || '', //客户订单ID 第一次保存的时候没有可以不传
                custSoNumber: this.$route.query.customerOrder.custSoNumber || '', //页面初始化流水号
                operType: "1000",//操作类型 必传，1000新增，1200变更（单号必传），1300保持不变（单号必传，其余字段需要修改的传入）
                custOrderType: "50200001", //必填 客户订单类型 默认值：50200001
                orderSourceId: "10000", //订单受理运营商  默认值：10000
                createStaff: "", //创建人  缓存里面取staffId
                createOrgId: "", //创建组织标识   缓存取 orgId
                accepteRegionId: "", //受理区域标识  默认：空
                accepteLanId: "500181403", //受理本地网标识    默认：空
                custId: "", //客户id   客户定位页面带回
                custName: "", //客户名   客户定位页面带回
                sysSource: "1000", //来源系统，原extSystem  默认：1000
                channelId: "10", //渠道的业务编码  待确定
                orderSource: "1000", //订单来源	普通受理，集团主数据EVT-C-0001  默认：1000
                bussDesc: "", //业务描述  默认：空
                remark: "", //备注 ORDER_COMMENT，是否替换  默认：空
                contactId: "", //合同id 保存项目是会更新  默认：空
                contactCd: "", //合同cd 保存项目是会更新 默认：空
                contractNumberType: "", //合同编码类型
                contactName: "", //合同名称  默认：空
                projectId: "", //项目id 默认：空
                projectName: "", //项目名称 默认：空
                saleId: "", //商机id 默认：空
                extCustOrderId: "", //外部客户订单标识 默认：空
                respCustId: '', //省账户ID，存在ordproinst表
            },
        };
    },
    mounted() {
        let FormModel = JSON.parse(sessionStorage.getItem("FormModel"));
        this.res.createStaff = this.user.staffId; //创建人  缓存里面取staffId
        this.res.createOrgId = this.user.orgId; //创建人  缓存里面取staffId
        this.res.accepteRegionId = this.user.regionId; //受理区域标识  默认：空
        this.res.custId = this.orderPosInfo.custId; //客户id   客户定位页面带回
        this.orderItemInfors.custId = this.orderPosInfo.custId; //客户id   传给订单项信息公共组件
        this.orderItemInfors.custName = this.orderPosInfo.custName; //客户名称   传给订单项信息公共组件
        this.res.custName = this.orderPosInfo.custName; //客户名   客户定位页面带回
        this.res.contactId = FormModel.contractId || ""; //合同ID
        this.res.contactCd = FormModel.contractCd || ""; //合同cd,
        this.res.contractNumberType = FormModel.contractNumberType || ""; //合同编号类型,
        this.res.contactName = FormModel.contractName || ""; //合同名字
        this.res.projectId = FormModel.projectId || ""; //项目id
        this.res.projectName = FormModel.projectName || ""; //项目名称
        this.res.saleId = FormModel.saleId || ""; //商机id
        this.res.respCustId = this.respCustId || ""; //省账户ID
    },
    computed: {
        ...mapState("orders", ["orderPosInfo", "elecLabel", "respCustId"]),
        ...mapState("user", ["user", "busiManagerId", "custManagerId"]),
        ...mapState("collect", ["activeTemplateId"]),
    },
    watch: {
        activeTemplateId(val) {
            if (val) {
                this.getTmplData()
            }
        }
    },
    methods: {
        ...mapMutations('collect', ['setSaveChange']),
        getParam(data) { },
        /** 通过销售品Id获取产品信息  */
        async getProductInfo(offerId) {
            let params = {
                interFaceType: "CPCP",
                sqlId: 20210707003,
                paramStr: "offerId:" + offerId,
            };
            let result = await OrderService.executeSql(params);
            return result; 
        },
        Save() {
            //订单信息的校验结果
            const val = this.$refs['orderiteminfo'].validateAll()
            if (!val) {
                this.$notify.error({
                    title: "校验失败",
                    message: "订单信息数据填写有误,请按要求正确填写数据!",
                });
                return
            }
            let arr = [];
            this.res.result = [];
            for (let key in this.formData) {//20210819 add by cjj
                if (key.split("-")[1] == "10000001379") {
                    this.formData[key].value = this.formData[key].value.toString();//5G产品类型值数组转换字符串
                }
            }
            arr[0] = this.formData;
            //先根据产品id把对象处理成数组，数组里的对象个数对应就是产品的个数
            arr.forEach((item) => {
                this.res.result.push(Object.values(item));
            });


            this.saveProd();
        },
        //报文数据拼接结束
        async formatData() {
            let ppmParams = JSON.parse(sessionStorage.getItem('ppmCondition'));
            let arr = [];
            this.res.result = [];
            arr[0] = this.formData;
            //先根据产品id把对象处理成数组，数组里的对象个数对应就是产品的个数
            arr.forEach((item) => {
                this.res.result.push(Object.values(item));
            });
             //获取不同产品id 20210826 add by cjj
             let prodRES = await this.getProductInfo(ppmParams.offerId);
             if (prodRES.code == 200) {
                 if (prodRES.meta.resList) {
                     if (prodRES.meta.resList.executeSqlResp.length > 0) {
                         let prodInfo = prodRES.meta.resList.executeSqlResp[0];
                         ppmParams.prodId = prodInfo.prodId;//0端产品
                         ppmParams.zProdId = prodInfo.zProdId;// 100 ,200 产品
                     }
                 }
             } else {
                 this.$message('prodId查询失败');
             }
 
            let params = prodSave.buildObject(
                this.res,
                this.res.agentList,
                this.busiManagerId,
                this.custManagerId,
                ppmParams
            );
            return params
        },
        //报文提交预览
        preview() {
            const params = this.formatData()
            this.$alert(params, {
                dangerouslyUseHTMLString: true,
                lockScroll: false,
                customClass: "messageBox-content-a",
            });
        },

        // 报文提交
        async saveProd() {
            let ppmParams = JSON.parse(sessionStorage.getItem('ppmCondition'));
            let citySelectA = JSON.parse(sessionStorage.getItem('citySelectA'));
            let citySelectB = JSON.parse(sessionStorage.getItem('citySelectB'));
            let accReq = sessionStorage.getItem('accReq');
            let accVal = sessionStorage.getItem('accVal');
            //获取不同产品id 20210826 add by cjj
            let prodRES = await this.getProductInfo(ppmParams.offerId);
            if (prodRES.code == 200) {
                if (prodRES.meta.resList) {
                    if (prodRES.meta.resList.executeSqlResp.length > 0) {
                        let prodInfo = prodRES.meta.resList.executeSqlResp[0];
                        ppmParams.prodId = prodInfo.prodId;//0端产品
                        ppmParams.zProdId = prodInfo.zProdId;// 100 ,200 产品
                    }
                }
            } else {
                this.$message('prodId查询失败');
            }

            let params = prodSave.buildObject(
                this.res,
                this.res.agentList,
                this.busiManagerId,
                this.custManagerId,
                ppmParams
            );
            // if(this.formData['104324520'].value == ''){
            //     this.$confirm("订单申请数量不能为空", "提示", {
            //         confirmButtonText: "关闭",
            //         showCancelButton: false,
            //         type: 'warning',
            //         center: true,
            //     })
            //     return
            // }
            // if (!this.formData["ORDER_ITEM-ORDER_DATE"].value) {
            //     this.$confirm("要求完成时间不能为空", "提示", {
            //         confirmButtonText: "关闭",
            //         showCancelButton: false,
            //         type: 'warning',
            //         center: true,
            //     })
            //     return
            // }
            if (this.formData['100013695'].required && this.formData['100013695'].value == '') {
                this.$confirm("发展人不能为空", "提示", {
                    confirmButtonText: "关闭",
                    showCancelButton: false,
                    type: 'warning',
                    center: true,
                })
                return
            }
            // let hireTime = params.mainOfferInsts[0].ordProdInsts[0].hireTime ? params.mainOfferInsts[0].ordProdInsts[0].hireTime : '';
            // if (hireTime.length > 1 && (hireTime.indexOf("日") != -1 || hireTime.indexOf("月") != -1 || hireTime.indexOf("年") != -1)) {} else {
            //     this.$confirm("租用期限不能为空", "提示", {
            //         confirmButtonText: "关闭",
            //         showCancelButton: false,
            //         type: 'warning',
            //         center: true,
            //     })
            //     return
            // }
            if (accReq == 'true' && accVal == 0) {
                this.$confirm("省付费账户不能为空", "提示", {
                    confirmButtonText: "关闭",
                    showCancelButton: false,
                    type: 'warning',
                    center: true,
                })
                return
            }
            if (citySelectA && citySelectB) {
                if (citySelectA.address.provice == '') {
                    this.$confirm("甲端城市：省份不能为空！", "提示", {
                        confirmButtonText: "关闭",
                        showCancelButton: false,
                        type: 'warning',
                        center: true,
                    })
                    return
                }
                if (citySelectB.address.provice == '') {
                    this.$confirm("乙端城市：省份不能为空！", "提示", {
                        confirmButtonText: "关闭",
                        showCancelButton: false,
                        type: 'warning',
                        center: true,
                    })
                    return
                }
                if (citySelectA.address.country == '26068' && citySelectA.address.provice != 25991 && citySelectA.address.provice != 25878 && citySelectA.address.provice != 26264 && citySelectA.address.provice != 27528 && citySelectA.address.provice != 26177 && citySelectA.address.provice != 24976 && citySelectA.address.city == '') {
                    this.$confirm("甲端城市：市不能为空！", "提示", {
                        confirmButtonText: "关闭",
                        showCancelButton: false,
                        type: 'warning',
                        center: true,
                    })
                    return
                }
                if (citySelectB.address.country == '26068' && citySelectB.address.provice != 25991 && citySelectB.address.provice != 25878 && citySelectB.address.provice != 26264 && citySelectB.address.provice != 27528 && citySelectB.address.provice != 26177 && citySelectB.address.provice != 24976 && citySelectB.address.city == '') {
                    this.$confirm("乙端城市：市不能为空！", "提示", {
                        confirmButtonText: "关闭",
                        showCancelButton: false,
                        type: 'warning',
                        center: true,
                    })
                    return
                }
            }
            let loadingInstance = Loading.service({
                fullscreen: true
            });
            const result = await OrderService.saveOrderList(params);

            if (result.code == 200) {
                if (result.meta.resultCode == 0) {
                    loadingInstance.close();
                    // this.$message({
                    //     type: "success",
                    //     message: "受理成功!",
                    // });
                    this.$confirm("受理成功!", "提示", {
                        confirmButtonText: "确定",
                        showCancelButton: false,
                        showClose: false,
                        closeOnClickModal: false,
                        type: "success",
                    }).then(() => {
                        this.customerOrder = result.meta.customerOrder;
                        this.$store.commit("orders/SET_STEPACTIVE", 2);
                        // 信息录入需要清缓存刷新数据
                        this.$router.options.routes.map((item) => {
                            if (item.name == "inforentryppm") {
                                item.meta.isFefresh = true;
                            }
                        });
                        this.$router.push({
                            path: "/orderadd",
                            query: {
                                customerOrder: this.customerOrder,
                            },
                        });
                    }).catch(() => { });
                } else {
                    this.$message({
                        type: "error",
                        message: "保存失败!" + result.meta.resultMsg,
                    });
                    loadingInstance.close();
                }
            } else {
                this.$message.error("受理失败!请重新尝试");
                loadingInstance.close();
            }
        },

        goback() {
            this.$store.commit("orders/SET_STEPACTIVE", 2);
            this.$router.push({
                path: "/orderadd",
                query: {
                    customerOrder: this.customerOrder,
                },
            });
        },

        //收藏
        async collect(info) {
            if (!this.$refs['PPMPage']) {
                return
            }
            const {
                name
            } = info
            //取出this.formData中每项的value和text进行保存
            const data = {}
            Object.keys(this.formData).forEach(key => {
                data[key] = {
                    value: this.formData[key].value,
                    text: this.formData[key].text,
                    options: this.formData[key].options
                }
            })
            const {
                productId
            } = JSON.parse(sessionStorage.getItem('ppmCondition'));
            const params = {
                contentJson: JSON.stringify(data),
                createDate: "",
                createStaff: this.user.staffId,
                prodId: productId,
                remark: "",
                statusCd: 1,
                templateId: '',
                templateName: name,
                updateDate: "",
                updateStaff: 0
            }
            let loadingInstance = Loading.service({
                fullscreen: true
            });
            try {
                let res = null
                if (this.activeTemplateId) { //如果模板id存在则更新否则新增 
                    params.templateId = this.activeTemplateId
                    res = await OrderService.orderTemplateUpdate(params)
                } else {
                    res = await OrderService.addOrderTemplate(params)
                }
                if (res.code == 200) {
                    // 通知列表刷新
                    this.setSaveChange()
                    this.$message.success("收藏成功！");
                } else {
                    this.$message.error("收藏失败!请重新尝试");
                }
                loadingInstance.close()
            } catch {
                loadingInstance.close()
            }
        },

        /**
         * 点击模板请求数据回显
         */
        async getTmplData() {
            let loadingInstance = Loading.service({
                fullscreen: true
            });
            try {
                const {
                    code,
                    meta
                } = await OrderService.orderTemplateDetail(this.activeTemplateId)
                if (code == 200) {
                    const {
                        contentJson
                    } = meta
                    deepAssign(this.formData, JSON.parse(contentJson))
                    // this.$forceUpdate()
                } else {
                    this.$message.error("获取模板详情失败!请重新尝试");
                }
                loadingInstance.close()
            } catch {
                loadingInstance.close()
            }
        },

    },
};